//
//  AddressManagementViewController.m
//  Yanwei
//
//  Created by 刘文 on 17/5/4.
//  Copyright © 2017年 DCloud. All rights reserved.
//

#import "AddressManagementViewController.h"
#import "AddressManagementCell.h"
#import "EditAddressViewController.h"
#import "MuchStoreRequestManager.h"
#import "UITableViewRowAction+JZExtension.h"

@interface AddressManagementViewController () <UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) UITableView * tableView;
@property (assign, nonatomic) AddressManagementType addressManagementType;
@property (nonatomic, assign) NSInteger selectedRow;
@property (nonatomic, strong) UIButton *addButton;

@end

@implementation AddressManagementViewController

- (instancetype)initWithAddressManagementType:(AddressManagementType)addressManagementType {
    self = [super init];
    if (self) {
        self.addressManagementType = addressManagementType;
    }
    return self;
}

- (void)_reLayout {
    self.navigationView.title = @"地址管理";
    self.view.backgroundColor = Color244;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [MuchStoreRequestManager storeGetAddressList:^(NSMutableArray *data) {
            [self.tableView.mj_header endRefreshing];
            if (data.count > 0) {
                self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
                [self.tableView.dataArray removeAllObjects];
                self.tableView.dataArray = data;
                [self.tableView reloadData];
            } else {
                UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
                
                UILabel *lab = [UILabel singleLineText:@"暂时没有数据!" font:APPFONT(15) wid:200 color:HEXCOLOR(0x333333)];
                lab.center = view.center;
                [view addSubview:lab];
                self.tableView.tableFooterView = view;
            }
        } fail:^(NSString *error) {
            [self.tableView.mj_header endRefreshing];
        }];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.addressManagementType == AddressManagementTypeSelect && self.callbackAddress) {
        if (self.tableView.dataArray.count != 0) {
            StoreAddressModel *model = [self.tableView.dataArray objectAtIndex:self.selectedRow];
            self.callbackAddress(model);
        } else {
            self.callbackAddress(nil);
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}


#pragma mark - progress
- (void)progressEditButton:(UIButton *)sender {
    EditAddressViewController *vc = [[EditAddressViewController alloc] initWithEditAddressType:EditAddressTypeEdit];
    vc.model = self.tableView.dataArray[sender.tag];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)progressAddAddressButton {
    EditAddressViewController *vc = [[EditAddressViewController alloc] initWithEditAddressType:EditAddressTypeAdd];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableView.dataArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [AddressManagementCell cellHeight:self.tableView.dataArray[indexPath.row]];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString * identifier = @"AddressManagementCell";
    AddressManagementCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[AddressManagementCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    cell.model = self.tableView.dataArray[indexPath.row];
    
    cell.editButton.tag = indexPath.row;
    [cell.editButton addTarget:self action:@selector(progressEditButton:) forControlEvents:UIControlEventTouchDown];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001f;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * view = [[UIView alloc] init];
    view.backgroundColor = Color244;
    return view;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self setEditing:false animated:true];
}
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
//    UIImage *image = [UIImage imageNamed:@"cell_delete"];
//    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault image:image handler:^(UITableViewRowAction * _Nullable action, NSIndexPath * _Nullable indexPath) {
//        StoreAddressModel *model = tableView.dataArray[indexPath.row];
//        [StoreRequestManager storeDeleteAddress:model.sid success:^(id  _Nonnull responseObject) {
//            [self setEditing:false animated:true];
//
//            [tableView.dataArray removeObjectAtIndex:indexPath.row];
//            [tableView reloadData];
//        } fail:^(NSString *error) {}];
//    }];
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        StoreAddressModel *model = tableView.dataArray[indexPath.row];
        [MuchStoreRequestManager storeDeleteAddress:model.sid success:^(id  _Nonnull responseObject) {
            [self setEditing:false animated:true];
            
            [tableView.dataArray removeObjectAtIndex:indexPath.row];
            [tableView reloadData];
        } fail:^(NSString *error) {}];
    }];
    action1.backgroundColor = Color244;
    
    return @[action1];
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 1100
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (@available(iOS 11.0, *)) {
        UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:nil handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
            StoreAddressModel *model = tableView.dataArray[indexPath.row];
            [MuchStoreRequestManager storeDeleteAddress:model.sid success:^(id  _Nonnull responseObject) {
                [self setEditing:false animated:true];
                
                [tableView.dataArray removeObjectAtIndex:indexPath.row];
                [tableView reloadData];
            } fail:^(NSString *error) {}];
            completionHandler(YES);
        }];
        //也可以设置图片
//        deleteAction.image = [UIImage imageNamed:@"cell_delete"];
        deleteAction.title = @"删除";
        UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction]];
        return config;
    } else {
        // Fallback on earlier versions
        return nil;
    }
}
#endif
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.addressManagementType == AddressManagementTypeSelect && self.callbackAddress) {
        StoreAddressModel * model = [tableView.dataArray objectAtIndex:indexPath.row];
        self.callbackAddress(model);
        self.selectedRow = indexPath.row;
        [self.navigationController popViewControllerAnimated:YES];
    }
}


#pragma mark - 懒加载
- (UITableView *)tableView {
    if(!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = Color244;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.dataArray = [[NSMutableArray alloc] init];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.navigationView.mas_bottom);
            make.left.and.right.equalTo(self.view);
            make.bottom.equalTo(self.addButton.mas_top);
        }];
    }
    return _tableView;
}
- (UIButton *)addButton {
    if (!_addButton) {
        _addButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [_addButton setTitle:@"添加新地址" forState:UIControlStateNormal];
        [_addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_addButton.titleLabel setFont:APPFONT(15)];
        _addButton.backgroundColor = Color175030;
        [_addButton addTarget:self action:@selector(progressAddAddressButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_addButton];
        [_addButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view).with.offset(15);
            make.right.equalTo(self.view).with.offset(- 15);
            make.bottom.equalTo(self.view).with.offset(- 15);
            make.height.mas_equalTo(45);
        }];
    }
    return _addButton;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
